<?php
namespace App\Http\Controllers\Api;

use App\Models\User\WxUserCoinRecord;
use App\Models\WxTask;
use App\Models\User\WxUserSignRecord;
use App\Models\User\WxUserTask;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SignTaskController extends BaseController{

    private function sign_data($uid){
        $result_ = [
        ];

        $cur_time = current_time();
        $w = date('w', strtotime($cur_time));
        if($w == 0){
            $w = 6;
        }else{
            $w -= 1;
        }
        $days = Utils::getWeekDays(strtotime($cur_time));
        $sign_data = [];
        $app_user_sign = Settings::get('app_user_sign', []);
        $today_is_sign = UserUtils::is_signed($uid, $cur_time);

        for($i = 0; $i < 7; $i ++){
            $reward = [];
            if(isset($app_user_sign[$i])){
                $reward = $app_user_sign[$i];
            }
            $is_signed = UserUtils::is_signed($uid, $days[$i]);
            $day = $is_signed ? '已签' : ('第'.($i + 1).'天');
            // 0：过期未签 1：已签到 2：可签到 3: 未达到时间
            $state = 0;
            if($is_signed){
                $state = 1;
            }else{
                if($w == $i){
                    $state = 2;
                    $day = '可签';
                }else{
                    if($days[$i] < $cur_time){
                        $state = 0;
                        $day = '漏签';
                    }else{
                        $state = 3;
                    }
                }
            }

            $sign_data[] = [
                'day' => $day,
                'reward' => $reward,
                'integral'=> _array_key($reward, 'num', 0),
                'extra' => 0,
                'state' => $state
            ];

        }


        $result_['list'] = $sign_data;
        $result_['today_signed'] = $today_is_sign ? 1 : 0;

        $coins_total_sign = WxUserCoinRecord::where([
            ['user_id', '=', $uid],
            ['type', '=', 7],
        ])->sum('incre');

        $result_['coins_total'] = $coins_total_sign;

        return $result_;
    }

    public function task_data($user_id){
        $task_ids = explode(',', Settings::get('app_sign_day_task', ''));
        $result = [];
        foreach ($task_ids as $task_id){
            $task = WxTask::find($task_id);
            if($task){

                $res1 = Utils::isTaskComplete($user_id, $task_id);
                if($res1['code'] == 1){
                    $task->status = 1;
                }else{
                    $res2 = Utils::isTaskComplete($user_id, $task_id, true);
                    if($res2['code'] == 1){
                        $task->status = 2;
                        $task->condition_tip = $res2['current'].'/'.$res2['condition'];
                    }else{
                        $task->status = 0;
                        $task->condition_tip = $res2['current'].'/'.$res2['condition'];
                    }
                }
                $task->reward_tip = FieldUtils::getGiftTypes()[(int)$task->reward_type] . '*' . $task->reward_num;
                $result[] = $task;
            }

        }
        return $result;
    }

    public function user_sign_continuous_days($uid){

        if(_empty_($uid)){
            return 0;
        }

        $records = DB::table('wx_user_sign_record')
            ->where('user_id', $uid)
            ->orderByDesc('created_at')
            ->get();

        $continuous_days = 0;
        $previous_date = null;

        foreach ($records as $record) {
            $current_date = $record->created_at;

            // 检查日期是否连续
            if ($previous_date !== null && $this->isNextDay($current_date, $previous_date)) {
                $continuous_days++;
            } elseif ($previous_date === null) {
                $continuous_days++;
            } else {
                break; // 遇到不连续的日期，结束循环
            }

            $previous_date = $current_date;
        }

        return $continuous_days;
    }

    private function isNextDay($current_date, $previous_date)
    {

        $current_timestamp = strtotime(explode(' ', $current_date)[0]);
        $previous_timestamp = strtotime(explode(' ', $previous_date)[0]);

        return _abs($current_timestamp - $previous_timestamp) === 86400;
    }

    public function user_data($uid){
        $result = [];

        $experience = get_user_meta($uid, 'experience', 'n');
        if(_empty_($experience)){
            $experience = 1;
        }

        $result['experience'] = $experience;
        $result['signedDays'] = WxUserSignRecord::where('user_id', $uid)->count();
        $result['taskTotal'] = WxUserTask::where('user_id', $uid)->count();;
        $result['coins'] = UserUtils::user_coins($uid);
        $result['lv'] = UserUtils::lv($uid);

        if(_empty_($result['signedDays'])){
            $result['signedDays'] = 0;
        }
        if(_empty_($result['taskTotal'])){
            $result['taskTotal'] = 0;
        }


        if($result['lv'] == 1){
            $result['nextLvExp'] = 60;
        }else if($result['lv'] == 2){
            $result['nextLvExp'] = 800;
        }else if($result['lv'] == 3){
            $result['nextLvExp'] = 3500;
        }else if($result['lv'] == 4){
            $result['nextLvExp'] = 10800;
        }else if($result['lv'] == 5){
            $result['nextLvExp'] = 38800;
        }else if($result['lv'] == 6){
            $result['nextLvExp'] = 999999999;
        }

        $result['nextLv'] = $result['lv'] >= 6 ? '6+' : $result['lv'] + 1;
        $result['nextLvExpNeed'] = $result['nextLvExp'] - $result['experience'];
        $result['rate'] = (int)( $experience / $result['nextLvExp'] * 100 );


        // 连续签到天数
        $result['continuous_days'] = $this->user_sign_continuous_days($uid);

        return $result;
    }

    /** 获取签到任务页面的数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sign_task_data(Request $request){
        $uid = $request->uid;
        $result = [];
        try {
            $result['sign'] = $this->sign_data($uid);
            $result['task'] = $this->task_data($uid);
            $result['user'] = $this->user_data($uid);
        }catch (\Exception $e){

        }

        return $this->success($result);
    }

    /** 获取任务大厅
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function task_hall(Request $request){
        $user_id = $request->uid;
        $type = $request->type;
        if(_empty_($type, true)){
            return $this->fail(200001);
        }
        if($type == 0){
            // 每日任务
            $daytasks = WxTask::where('type', 0)->orderBy('created_at', 'desc')->simplePaginate(10);
            if($daytasks){
                $daytasks->map(function ($v, $k) use ($user_id){

                    $res1 = Utils::isTaskComplete($user_id, $v->id);
                    if($res1['code'] == 1){
                        $v->status = 1;
                    }else{
                        $res2 = Utils::isTaskComplete($user_id, $v->id, true);
                        if($res2['code'] == 1){
                            $v->status = 2;
                            $v->condition_tip = $res2['current'].'/'.$res2['condition'];
                        }else{
                            $v->status = 0;
                            $v->condition_tip = $res2['current'].'/'.$res2['condition'];
                        }
                    }

                    $v->reward_tip = FieldUtils::getGiftTypes()[(int)$v->reward_type] . '*' . $v->reward_num;
                    return $v;
                });
            }
            return $this->success($daytasks);
        }else{
            // 成长任务
            $oncetasks = WxTask::where('type', 1)->orderBy('created_at', 'desc')->simplePaginate(1000);
            $res_tasks = [];
            if($oncetasks){
                $map = [];
                $cache = [];
                foreach (FieldUtils::getOnceTaskTypes() as $k => $v){
                    $map[$k] = [
                        'status_2' => [],
                        'status_1' => [],
                        'status_0' => [],
                    ];
                    $cache[$k] = [
                        'status_0' => null,
                    ];
                }
                $oncetasks->map(function ($v, $k) use ($user_id, &$map){

                    $res1 = Utils::isTaskComplete($user_id, $v->id);
                    if($res1['code'] == 1){
                        $v->status = 1;
                    }else{
                        $res2 = Utils::isTaskComplete($user_id, $v->id, true);
                        if($res2['code'] == 1){
                            $v->status = 2;
                            $v->condition_tip = $res2['current'].'/'.$res2['condition'];
                        }else{
                            $v->status = 0;
                            $v->condition_tip = $res2['current'].'/'.$res2['condition'];
                        }
                    }

                    $v->reward_tip = FieldUtils::getGiftTypes()[(int)$v->reward_type] . '*' . $v->reward_num;

                    $map[$v->condition_type_1]['status_'.$v->status][] = $v;
                    return $v;
                });

                foreach (FieldUtils::getOnceTaskTypes() as $k => $v){
                    if($map[$k]['status_2']){
                        foreach ($map[$k]['status_2'] as $item){
                            $res_tasks[] = $item;
                        }
                    }
                }

                foreach (FieldUtils::getOnceTaskTypes() as $k => $v){
                    if($map[$k]['status_0']){
                        foreach ($map[$k]['status_0'] as $item){
                            if($cache[$k]['status_0']){
                                if($cache[$k]['status_0']->condition_num > $item->condition_num){
                                    $cache[$k]['status_0'] = $item;
                                }
                            }else{
                                $cache[$k]['status_0'] = $item;
                            }
                        }
                    }
                }

                foreach (FieldUtils::getOnceTaskTypes() as $k => $v){
                    if($cache[$k]['status_0']){
                        $res_tasks[] = $cache[$k]['status_0'];
                    }
                }

                foreach (FieldUtils::getOnceTaskTypes() as $k => $v){
                    if($map[$k]['status_1']){
                        foreach ($map[$k]['status_1'] as $item){
                            $res_tasks[] = $item;
                        }
                    }
                }



                $oncetasks = json_decode($oncetasks->toJson(), true);
                $oncetasks['data'] = $res_tasks;
            }
            return $this->success($oncetasks);
        }
    }

    public function sign(Request $request){

        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $uid = $request->uid;
        $date = current_time();
        if(UserUtils::is_signed($uid, $date)){
            return $this->fail(200010, [], '你今天已经签到过了');
        }
        DB::transaction(function () use($uid, $date){
            $model = new WxUserSignRecord();
            $model->user_id =$uid;
            $model->save();
            UserUtils::sign_reward($uid, $date);
        });
        return $this->success([ 'sign'=>$this->sign_data($uid), 'task'=>$this->task_data($uid), 'user'=>$this->user_data($uid) ]);
    }

    public function taskReward(Request $request){

        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $uid = $request->uid;
        $task_id = trim($request->task_id, ',');

        if(_empty_($task_id)){
            return $this->fail(200001);
        }

        if(strpos($task_id, ',') === false){
            if(Utils::isTaskComplete($uid, $task_id)['code'] == 1){
                return $this->fail(200010, [], '您已领取该任务奖励');
            }
            $r = Utils::isTaskComplete($uid, $task_id, true);
            if($r['code'] != 1){
                return $this->fail(200014);
            }
            $tip = UserUtils::task_reward($uid, $task_id);
            if($tip){
                $userTask = new WxUserTask();
                $userTask->user_id = $uid;
                $userTask->task_id = $task_id;
                $r_ = $userTask->save();
                if(_empty_($r_)){
                    $this->fail(200002);
                }
                return $this->success(['coins'=>UserUtils::user_coins($uid), 'task'=>$this->task_data($uid), 'user'=>$this->user_data($uid)], 200, '已获取 '.$tip.' 奖励');
            }else{
                $this->fail(200006);
            }
        }else{
            $task_id_arr = array_unique(explode(',', $task_id));
            if($task_id_arr){
                $rewrad_tip = '';
                foreach ($task_id_arr as $tid){
                    if(Utils::isTaskComplete($uid, $tid)['code'] == 1){
                        continue;
                    }
                    $r = Utils::isTaskComplete($uid, $tid, true);
                    if($r['code'] != 1){
                        continue;
                    }
                    $tip = UserUtils::task_reward($uid, $tid);
                    if($tip){
                        $userTask = new WxUserTask();
                        $userTask->user_id = $uid;
                        $userTask->task_id = $tid;
                        $r_ = $userTask->save();
                        if($r_){
                            if(_empty_($rewrad_tip)){
                                $rewrad_tip .= ',';
                            }
                            $rewrad_tip .= $tip;
                        }

                    }else{
                        _logger_(__file__, __line__, '出现任务领取奖励的错误');
                    }
                }
                if($rewrad_tip){
                    return $this->success([], 200, '已获取 '.$rewrad_tip.' 等奖励');
                }
            }
        }


    }

}
